#!/usr/bin/perl
#
# Register a machine entry
#
use strict;

use Counter;
use CGI;
use CGI::Carp;
use POSIX;
# Counter specific
use ErrorForm;
use Counter::Recordinfo;
use CounterCGI;

use vars qw($machines $users $entry $user $userno $operation);
use vars qw($mkey $newrec $newownerkey $secret $machine $newowner);

chdir($ENV{COUNTER_ROOT});

open(EVENTLOG, ">>logs/eventlog");
print EVENTLOG scalar(gmtime), " machine-counter.pl\n";

$machines = Counter::openfile("machines", O_RDWR|O_CREAT);
$users = Counter::openfile("users", O_RDWR|O_CREAT);

# Parse the entry
$entry = new CGI;

# Check whether key is correct
$user = CounterCGI::requirelogin($users, $entry);
$userno = $user->key();

$operation = $entry->param("operation");
if (!$operation) {
    # assume create (old form)
    $operation = "create";
}
if ($operation eq "create") {
    # no particular checking
    $machine = $machines -> newnum();
    $machine->{owner} = $user->key;
    $mkey = $machine->key;
    print EVENTLOG "Creating machine $mkey\n";
    $user->append("machines", $machine->key);
} elsif ($operation eq "update") {
    # Check that it's owned by the right person
    $mkey = $entry->param("machine");
    $machine = $machines->get($mkey);
    if (!$machine) {
	errorForm("No such machine: $mkey");
    } elsif ($machine->{owner} ne $user->key) {
	errorForm("Machine $mkey not owned by $userno");
    }
    print EVENTLOG "Updating machine $mkey\n";
} else {
    errorForm("illegal operation: $operation");
}

# Set field values from form

for my $field ($machines->fields) {
    my @values = $entry->param($field);
    next if $#values == -1;
    my $value = join(", ", @values);
    $value =~ s/, $//; # delete trailing blank entry
    $machine->{$field} = $value;
}
# Handle giving away machines
$newowner = $entry->param("newkey");
if ($newowner) {
    ($newownerkey = $newowner) =~ s/-\d+$//;
    $newrec = $users->get($newownerkey);
    if (!$newrec) {
	errorForm("New owner $newownerkey does not exist");
    } elsif ($newrec->{key} ne $newowner) {
	errorForm("Wrong key for new owner");
    } else {
	$machine->{owner} = $newownerkey;
	$user->{machines} =~ s/ ?$mkey//;
	$newrec->append("machines", $mkey);
    }
}

$machine->{method} = "machine-counter.cgi";
Counter::Recordinfo::addadmin($machine);
$machine->store;
$user->store;
$newrec->store if $newrec;

print <<EoF;
Content-type: text/html; charset="utf-8"

<html>
EoF

CounterCGI::pagehead("Machine $operation accepted");
print "<body bgcolor=white>\n";
CounterCGI::pagetop($entry);

print <<EoF;
<H1><img src="/gifs/Logo-small.gif">
Machine $operation accepted</H1>
EoF

if ($operation eq "create") {
    print <<EoF;
Thanks for filling out the registration form.
<p>
Your machine has registration number $mkey.
<p>
You can edit this machine from your <a href="/person/">home page</a>.
EoF
} elsif ($operation eq "update") {
    print "You have successfully updated machine $mkey.\n";
    if ($newowner) {
	print "<br>It now belongs to user $newownerkey\n";
    }
}
print <<EoF;
<p>
Now is a good time to install the
<a href="/scripts/">automatic update script</a> on that machine!
EoF

CounterCGI::pagebottom();
print "\n</body>\n</html>";

#$users -> close();
#$machines -> close();

sub getuser {
    my $sender = shift;
    my $user;
    my $key;

    $user = $users->getbykey("email", $sender);
    if ($user) {
        $key = $user->key;
        print EVENTLOG "userid is $key (old)\n";
    } else {
        $user = $users->newnum();
        $key = $user->key;
        $secret = int(100000*rand);
        $user->{key} = sprintf("%s-%05d", $user->key, $secret);
        $user->{email} = $sender;
        $user->{method} = "machine-counter.cgi";
        print EVENTLOG "userid is $key (new)\n";
    }
    $user;
}

